import React, { Component } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Button,
  Card,
  Row,
  Col,
  Select,
  Input,
  Table,
  Divider,
  Badge,
  Modal,
  Tooltip,
  Dropdown,
  Menu,
} from 'antd';
import { DownOutlined } from '@ant-design/icons';

import { CouriersListItem, CouriersListData } from './data';
import SetPasswordElem from './components/SetPasswordElem';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { Item } = Form;
const statusVal: any = ['error', 'success'];
const statusText = ['已禁用', '已启用'];

const { pathname } = window.location;

interface CouriersListProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: boolean;
  dataInfo: CouriersListData;
  INITINFO: any;
  screen: string;
  hasPath: boolean;
}

interface CouriersListState {
  searchValues: any;
  statusVisible: boolean;
  pwdVisible: boolean;
  detail: CouriersListItem | any;
  statusValses: any;
  delValues: any;
  delVisible: boolean;
  pageIndex:number;
  pageSize:number;
  rowId:number;
}

@connect(
  ({
    couriersMangagementList: { dataInfo },
    common: { INITINFO },
    loading,
    global: { screen, hasPath },
  }: any) => ({
    dataInfo,
    INITINFO,
    loading: loading.effects['couriersMangagementList/fetch'],
    screen,
    hasPath,
  }),
)
class CouriersListElem extends Component<CouriersListProps, CouriersListState> {
  columns = [
    {
      title: '员工姓名',
      dataIndex: 'realName',
      width: 100,
      render: (text: string, record: any) => (
        <Tooltip title={text}>
          <div
            className="wordOmit nameLink"
            onClick={() => this.handleEditCourier(record.userId, record.courierId, text)}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '员工手机号',
      dataIndex: 'phone',
      width: 120,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '所属物流中心',
      dataIndex: 'logisName',
      width: 180,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '岗位类型',
      dataIndex: 'positionName',
      width: 180,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '当前状态',
      dataIndex: 'status',
      width: 100,
      render: (text: number) => <Badge status={statusVal[text]} text={statusText[text]} />,
    },
    {
      title: '操作',
      width: 130,
      dataIndex: 'userId',
      render: (text: any, record: any) => (
        <>
          <span
            className="operLink"
            onClick={() => this.handleEditCourier(text, record.courierId, record.realName)}
          >
            编辑
          </span>
          <Divider type="vertical" />
          <span className="operLink" onClick={() => this.handleChangeStatusModal(true, record)}>
            {record.status ? '禁用' : '启用'}
          </span>
          <Divider type="vertical" />
          <Dropdown arrow overlay={() => this.menu(record)}>
            <span className="operLink">
              更多 <DownOutlined />
            </span>
          </Dropdown>
        </>
      ),
    },
  ];

  state: CouriersListState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    statusVisible: false,
    statusValses: {},
    pwdVisible: false,
    detail: {},
    delVisible: false,
    delValues: {},
    rowId: 0,
  }

  static getDerivedStateFromProps(nextProps: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;
    return {
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchAction('common/fetchLogisList');

    const { dataInfo, hasPath } = this.props;
    if (dataInfo?.list?.length && !hasPath) return;
    if (hasPath) {
      const { dispatch } = this.props;
      dispatch({ type: 'global/clearPath' });
    }

    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => {
    // 设置表单
    const { searchValues } = this.state;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(searchValues);
  };

  fetchDataValues = () => this.fetchAction('fetch', this.getQueryParams());

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    return params;
  };

  menu = (record: any) => (
    <Menu>
      <Menu.Item
        className="operLink"
        onClick={() => this.handleChangeDelModal(true, record)}
      >
        删除
      </Menu.Item>
      <Menu.Item
        className="operLink"
        onClick={() => this.handleChangePwdModal(true, record)}
      >
        设置密码
      </Menu.Item>
    </Menu>
  );

  /**
   * 添加快递员
   */
  handleAddCourier = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '新建快递员',
      url: '/basic/couriersManagement/list/add',
    });
  };

  /**
   * 编辑快递员
   */
  handleEditCourier = (id: number, courierId: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `编辑${name}`,
      url: `/basic/couriersManagement/list/add?userId=${id}&courierId=${courierId}`,
    });
  };

  handleChangeStatusModal = (statusVisible: boolean, values?: any) => {
    this.setState({
      statusVisible,
      statusValses: values
        ? {
          status: values.status === 1 ? 0 : 1,
          userId: values.userId,
          courierId: values.courierId,
        }
        : {},
    });
  };

  handleChangeStatus = () => {
    const { searchValues: search, statusValses } = this.state;
    const params = { search, ...statusValses };
    this.fetchAction('changeStatus', params);
    this.handleChangeStatusModal(false);
  };

  handleChangePwdModal = (pwdVisible: boolean, values?: any) => {
    this.setState({ pwdVisible, detail: values || {} });
  };

  handleChangeDelModal = (delVisible: boolean, values?: any) => {
    this.setState({
      delVisible,
      delValues: values
        ? {
          userId: values.userId,
          courierId: values.courierId,
        } : {},
    });
  };

  handleDelete = () => {
    const { searchValues: search, delValues } = this.state;
    const params = { search, ...delValues };
    this.fetchAction('delete', params);
    this.handleChangeDelModal(false);
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const query = {
        ...values,
        pageIndex: 1,
        pageSize: 20,
      };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '员工管理',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '员工管理',
      url: pathname,
      isTopMenu: true,
    });
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '员工管理',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  onClickRow = ({ key }: any) => ({
    onClick: () => {
      this.setState({ rowId: key });
    },
  })

  setRowClassName = ({ key }: any) => {
    const { rowId } = this.state;
    return key === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `couriersMangagementList/${typeName}`;
    dispatch({
      type,
      payload,
    });
  };

  render() {
    const {
      pageIndex,
      pageSize,
      statusVisible,
      pwdVisible,
      delVisible,
      detail,
      statusValses: { status },
    } = this.state;

    const {
      form: { getFieldDecorator },
      dataInfo,
      INITINFO: { logisList },
      loading,
    } = this.props;

    const dataSource = dataInfo
      ? dataInfo.list.map((item: any, index: number) => ({
        ...item,
        key: index + 1,
      }))
      : [];

    const pagination: object = {
      total: dataInfo ? dataInfo.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${dataInfo.count || 0}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="　物流中心" colon={false}>
                  {getFieldDecorator('logisId')(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {logisList.map((item: any) => (
                        <Option value={String(item.id)} key={item.id}>
                          {item.name}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　　姓名" colon={false}>
                  {getFieldDecorator('name')(<Input allowClear placeholder="请输入" />)}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　手机号" colon={false}>
                  {getFieldDecorator('phone')(
                    <Input allowClear type="number" placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={this.handleAddCourier}
            >
              添加
            </Button>
          </div>
          <Table
            rowKey="key"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 980 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        <SetPasswordElem
          visible={pwdVisible}
          detail={detail}
          changeModal={this.handleChangePwdModal.bind(this)}
        />

        <Modal
          title="修改状态"
          visible={statusVisible}
          okText="确定"
          onOk={this.handleChangeStatus}
          onCancel={() => this.handleChangeStatusModal(false)}
        >
          <p>确定{status ? '启用' : '禁用'}当前投递人吗？</p>
        </Modal>

        <Modal
          title="删除投递人"
          visible={delVisible}
          okText="删除"
          onOk={this.handleDelete}
          onCancel={() => this.handleChangeDelModal(false)}
        >
          <p>确定删除当前投递人吗？</p>
        </Modal>
      </>
    );
  }
}

export default Form.create<CouriersListProps>()(CouriersListElem);
